/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
*/

package com.jinhe.tss.core.cachepool.container;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jinhe.tss.core.cachepool.Cacheable;
import com.jinhe.tss.core.cachepool.CacheableKey;

/** 
 * <p> MapContainer.java </p> 
 *
 * 为了MapContainer能适用多线程，其每步对 map 的操作都必须锁定 map。
 * map本身不支持同步，ehcache则没有这个问题。
 * 
 *  @author Jon.King 2006-12-31
 */
public class MapContainer extends AbstractPoolContainer {
    
    private Map<CacheableKey, Cacheable> map;
    
    public MapContainer(String name) {
        super(name);
        map = Collections.synchronizedMap(new HashMap<CacheableKey, Cacheable>());
    }

    public Cacheable get(Object key) {
        Cacheable o = null;
        synchronized(map){
            o = (Cacheable) map.get(key);
        }
        return o;
    }

    public Cacheable put(Object key, Cacheable value) {
        synchronized(map){
            map.put((CacheableKey) key, value);
        }
        return value;
    }

    public Cacheable remove(Object key) {
        Cacheable o = null;
        synchronized(map){
            o = (Cacheable) map.remove(key);
        }
        return o;
    }

    public List<CacheableKey> getKeys() {
        List<CacheableKey> keys;
        synchronized(map){
            keys = new ArrayList<CacheableKey>(map.keySet());
        }
        return keys;
    }

    public void clear() {
        synchronized(map){
            map.clear();
        }
    }

    public int size() {
        int size = 0;
        synchronized(map){
            size = map.size();
        }
        return size;
    }

    public List<Cacheable> getValues() {
        List<Cacheable> values;
        synchronized(map){
            values = new ArrayList<Cacheable>(map.values());
        }
        return values;
    }
}

